﻿const httpStatus = require('http-status');
const ApiError = require('../utils/ApiError');
const catchAsync = require('../utils/catchAsync');
const { Role } = require('../models');

/**
 * 创建新角色
 */
const createRole = catchAsync(async (req, res) => {
  // 检查角色名是否已被使用
  if (await Role.isNameTaken(req.body.name)) {
    throw new ApiError(httpStatus.BAD_REQUEST, '角色名称已存在');
  }
  
  const role = await Role.create(req.body);
  res.status(httpStatus.CREATED).send(role);
});

/**
 * 获取所有角色
 */
const getRoles = catchAsync(async (req, res) => {
  const roles = await Role.find({ isDeleted: false }).sort({ createdAt: -1 });
  res.send(roles);
});

/**
 * 获取单个角色
 */
const getRole = catchAsync(async (req, res) => {
  const role = await Role.findOne({ _id: req.params.roleId, isDeleted: false });
  if (!role) {
    throw new ApiError(httpStatus.NOT_FOUND, '角色不存在');
  }
  res.send(role);
});

/**
 * 更新角色
 */
const updateRole = catchAsync(async (req, res) => {
  const role = await Role.findOne({ _id: req.params.roleId, isDeleted: false });
  if (!role) {
    throw new ApiError(httpStatus.NOT_FOUND, '角色不存在');
  }
  
  // 检查新的角色名是否与其他角色重复
  if (req.body.name && await Role.isNameTaken(req.body.name, req.params.roleId)) {
    throw new ApiError(httpStatus.BAD_REQUEST, '角色名称已存在');
  }
  
  Object.assign(role, req.body);
  await role.save();
  res.send(role);
});

/**
 * 删除角色
 */
const deleteRole = catchAsync(async (req, res) => {
  const role = await Role.findOne({ _id: req.params.roleId, isDeleted: false });
  if (!role) {
    throw new ApiError(httpStatus.NOT_FOUND, '角色不存在');
  }
  
  // 不允许删除超级管理员角色（可以根据实际需求增加更多保护措施）
  if (role.name === '超级管理员') {
    throw new ApiError(httpStatus.BAD_REQUEST, '系统角色无法删除');
  }
  
  // 逻辑删除
  role.isDeleted = true;
  await role.save();
  res.status(httpStatus.OK).send({ message: '角色删除成功' });
});

module.exports = {
  createRole,
  getRoles,
  getRole,
  updateRole,
  deleteRole,
}; 
